package org.softmed.ATComm;

import gnu.io.CommPortIdentifier;
import gnu.io.RXTXCommDriver;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class DefaultRXTXSerialConnectionManager implements
		SerialConnectionManager {

	CommPortIdentifier portId1;
	SerialPort serialPort1;
	String serialPortName;

	public List<String> getSerialPorts() {
		List<String> portNames = new ArrayList<String>();

		Enumeration<CommPortIdentifier> ports = CommPortIdentifier
				.getPortIdentifiers();

		while (ports.hasMoreElements()) {
			portNames.add(ports.nextElement().getName());
		}

		return portNames;

	}

	public void connect() throws Throwable {
		
		RXTXCommDriver gnuDriver = new RXTXCommDriver();

		CommPortIdentifier.addPortName(serialPortName,
				CommPortIdentifier.PORT_SERIAL, gnuDriver);

		portId1 = CommPortIdentifier.getPortIdentifier(serialPortName);

		System.out.println("Owner = " + portId1.getCurrentOwner());
		serialPort1 = (SerialPort) portId1.open("ATComControl", 2000);

		serialPort1.setSerialPortParams(9600, SerialPort.DATABITS_8,
				SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

		serialPort1.notifyOnDataAvailable(true);
		serialPort1.notifyOnOutputEmpty(true);
		
		

	}

	public void disconnect() throws Throwable {
//		serialPort1.
		serialPort1.close();
	}

	@Override
	public String getSerialPortName() {
		return serialPortName;
	}

	@Override
	public void setSerialPortName(String port) {
		this.serialPortName = port;

	}

	@Override
	public InputStream getInputStream() throws IOException {
		return serialPort1.getInputStream();
	}

	@Override
	public OutputStream getOutputStream() throws IOException {
		return serialPort1.getOutputStream();
	}

}
